<?php
defined('_JEXEC') or die( 'Restricted access' );

class TablePlantPlan extends Fcore
{
	/** @var int Primary key */
	var $id					= 0;
	/** @var int */
	var $fid				= '';
	/** @var string */
	var $pid				= 0;
	/** @var string */
	var $uid				= '';
	/** @var string */
	var $pre_sowing_date	= '';
	/** @var time */
	var $pre_harvest		= '';
	/** @var boolean */
	var $pre_production		= '';

	/**
	* @param database A database connector object
	*/
	function __construct( &$db )
	{
		parent::__construct( '#__farm_plant_plan', 'id', $db );
	}

	/**
	 * Binds an array to the object
	 * @param 	array	Named array
	 * @param 	string	Space separated list of fields not to bind
	 * @return	boolean
	 */
	function bind( $array, $ignore='' )
	{
		$result = parent::bind( $array );
		// cast properties
		$this->id	= (int) $this->id;
		return $result;
	}

	/**
	 * Overloaded check function
	 *
	 * @access public
	 * @return boolean
	 * @see JTable::check
	 * @since 1.5
	 */
	function check()
	{
		if (!intval( $this->fid ))
		{
			$this->setError(JText::_( '请选择农场' ));
			return false;
		}
		
		if (!intval( $this->pid ))
		{
			$this->setError(JText::_( '请选择植物' ));
			return false;
		}
		
		if (!intval( $this->uid ))
		{
			$this->setError(JText::_( '请选择记录人员' ));
			return false;
		}
		
		if (trim( $this->pre_sowing_date ) == '')
		{
			$this->setError(JText::_( '请输入计划播种日' ));
			return false;
		}
		
		if (trim( $this->pre_harvest ) == '')
		{
			$this->setError(JText::_( '请输入计划收割日' ));
			return false;
		}
		
		if (trim( $this->pre_production ) == '')
		{
			$this->setError(JText::_( '请输入预产量' ));
			return false;
		}
		return true;
	}
	
	/**
	 * 获取某种植计划信息及未执行操作
	 * @param type $ppid
	 * @return type 
	 */
	public function getFutureRecord($ppid)
	{
		$ppid = intval($ppid);
		
		if (!$ppid) return array();
		
		//种植计划信息
		$ppInfo = $this->getInfo($ppid);
		
		if (empty($ppInfo)) return array();
		
		$ppInfo['uid'] = $this->getUserName($ppInfo['uid']);
		
		//未执行操作
		$tPr = JTable::getInstance('plantplanOpe', 'Table');
		$notExecList = array('ope' => $tPr->getNotExecList($ppid));
		//var_dump($notExecList);
		
		//var_dump(array_merge($ppInfo, $notExecList));die;
		
		return array_merge($ppInfo, $notExecList);
	}
	
	public function pplist()
	{
//		$tmpTbl = $this->_tbl;
//		
//		$this->_tbl = '#__farm_plan';
		
		$data = $this->alist();

//		$this->_tbl  = $tmpTbl;
		if (empty($data[1])) return $data;
		
		//用户名
		$db	= JFactory::getDBO();
		$query = 'SELECT id, name no' .	' FROM #__users';
		$db->setQuery($query);
		$userArr = $this->getOpt($db->loadAssocList(), 'id', 'no');
		
		$tField = JTable::getInstance('field', 'Table');
		$tPlant = JTable::getInstance('plant', 'Table');
		foreach ((array)$data[1] as $k => $v) {
			
			$ppoids = $this->getOpes($v->id);
			
			$ppope = '';
			if (is_array($ppoids) && !empty ($ppoids)) {
				foreach ($ppoids as $v3) foreach ($v3 as $v2) {
					$ppope .= "<span style='color:" . ($v2['prid']?'green':'red') . "'>";
					$ppope .= "预计在{$v2['preDate']}执行\t";
					$ppope .= $v2['prid']?"实际执行于{$v2['excDate']}":'还未执行';
					$ppope .= "\t";
					$ppope .= $v2['custom'];
					$ppope .= "</span>" . "<br />";
				}
			}
			
			$data[1][$k] = (object)array(
				'id'		=> $v->id,	//操作编号
				'fid'		=> $tField->GetOne($v->fid, 'no'),		//农场编号
				'pid'		=> $tPlant->GetOne($v->pid, 'name'),	//植物名称
				'uid'		=> $userArr[$v->uid],					//记录人员
				'date1'		=> $v->pre_sowing_date,					//计划播种日
				'date2'		=> $v->pre_harvest,						//计划收割日
				'prod'		=> $v->pre_production,					//预产量
				'ope'		=> $ppope,								//计划明细
			);
		}
		return $data;
	}
	
	/**
	 * 获取农场和植物信息
	 * @param int $ppid 
	 */
	public function getInfo($ppid)
	{
		$plantPlanInfo = $this->getRow(intval($ppid), '*');
		
		if (!$plantPlanInfo) return null;
		
		$tField = JTable::getInstance('field', 'Table');
		$tPlant = JTable::getInstance('plant', 'Table');
		
		return array(
			'field' => $tField->GetOne($plantPlanInfo['fid'], 'no'),
			'plant' => $tPlant->GetOne($plantPlanInfo['pid'], 'name')
		) + $plantPlanInfo;
	}
	
	/**
	 * 获取种植计划具体计划
	 * @param int $ppid
	 * @param int $ppoid
	 * @return array 
	 */
	public function getOpes($ppid, $ppoid = 0)
	{
		//种植计划
		$tmpTbl = $this->_tbl;
		$this->_tbl = '#__farm_plan';
		$where = "WHERE ppid=" . intval($ppid);
		if ($ppoid) $where .= " AND prid=" . intval($ppoid);
		$data = $this->getAll($where);
		$this->_tbl  = $tmpTbl;
		if (empty($data)) return array();
		
		//加入施肥及农药信息
		$manureArr	= $pesticideArr = $return = array();
		$tManure	= JTable::getInstance('manure', 'Table');
		$tPesticide	= JTable::getInstance('pesticide', 'Table');
		foreach ((array)$data as $k => $v) {
			switch ($v['type']) {
				case 0://自定义
					break;
				case 1://施肥					
					empty($manureArr[$v['oid']]) && 
						$manureArr[$v['oid']] = $tManure->getOne($v['oid'], 'name');					
					$v['custom'] = $manureArr[$v['oid']];
					break;
				case 2://农药
					empty($pesticideArr[$v['oid']]) && 
						$pesticideArr[$v['oid']] = $tPesticide->getOne($v['oid'], 'name');
					$v['custom'] = $pesticideArr[$v['oid']];
					break;
			}
			$preTime = strtotime($v['date']);
			$return[$preTime][$v['id']] = array(
				'custom'	=> $v['custom'],
				'preDate'	=> $v['date'],
				'excDate'	=> $v['execution_time'],
				'prid'		=> $v['prid']
			);			
		}
		
		ksort($return);
		
		return $return;
	}
	
	
	/**
	 * 创建新的种植计划
	 * @param type $data 
	 */
	public function newPlantPlan()
	{
		//保存基本信息
		if (!$this->save($_POST)) die('1');
		
		//上一条插入数据ID
		$ppid = $this->getLastInsertID();
		
		if (!$ppid) die('1');
		
		//保存操作信息
		$res = $this->savePlan($ppid);
		
		return $res;
	}
	
	/**
	 * 保存操作信息
	 * @param int $ppid 种植计划ID
	 * @return boolean
	 */
	private function savePlan($ppid)
	{
		//分析POST数据
		$sql = "INSERT INTO #__farm_plan(ppid,date,type,oid,custom) VALUES ";
		
		$dArr = array();
		
		//施肥操作 
		if (!empty($_POST['manure']) && is_array($_POST['manure'])) {
			foreach ($_POST['manure'] as $key => $val) {
				if (empty($_POST['manureDate'][$key]) || !is_array($_POST['manureDate'][$key])) continue;
				foreach ($_POST['manureDate'][$key] as $time) 
					if (!empty($time)) $dArr[] = "($ppid, '$time', 1, $val, '')";
			}
		}
		
		//农药操作 
		if (!empty($_POST['pesticide']) && is_array($_POST['pesticide'])) {
			foreach ($_POST['pesticide'] as $key => $val) {
				if (empty($_POST['pesticideDate'][$key])|| !is_array($_POST['pesticideDate'][$key])) continue;
				foreach ($_POST['pesticideDate'][$key] as $time)
					if (!empty($time)) $dArr[] = "($ppid, '$time', 2, $val, '')";
			}
		}
		
		//自定义操作 
		if (!empty($_POST['userDefined']) && is_array($_POST['userDefined'])) {
			foreach ($_POST['userDefined'] as $key => $val) {
				if (empty($_POST['userDefinedDate'][$key])|| !is_array($_POST['userDefinedDate'][$key])) continue;
				foreach ($_POST['userDefinedDate'][$key] as $time)
					if (!empty($time)) $dArr[] = "($ppid, '$time', 0, 0, '$val')";
			}
		}
		
		if (empty($dArr)) return false;
		
		$sql .= join(',', $dArr);
		
		return $this->excuteQuery($sql);
	}
	
	/**
	 * 种植计划名及ID
	 */
	public function dataForOptions()
	{
		$query = 'SELECT pp.id, CONCAT(f.no, "-", p.name, "-", u.name) AS no FROM ' . $this->_tbl . ' AS pp 
			LEFT JOIN #__users AS u ON u.id=pp.uid 
			LEFT JOIN #__farm_field AS f ON f.id=pp.fid 
			LEFT JOIN #__farm_plant AS p ON p.id=pp.pid';
		$this->_db->setQuery( $query );
		if (!$this->_db->query())$this->_error .= $this->_db->getErrorMsg() . "\n";		
		return $this->_db->loadAssocList();
	}
}
